<?php

namespace App\Http\Controllers\Api\Admin;

use App\Facades\UserService;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Sentinel;

class UserController extends Controller
{
    public function updatePassword(Request $request)
    {
    	$rules = [
    		'password' => 'required|min:6',
    		'newPassword' => 'required|min:6|confirmed'
    	];
    	$this->validate($request, $rules);

    	UserService::updatePassword($request->password, $request->newPassword);
    	return formatJsonResponse();
    }

    public function add(Request $request)
    {
    	$rules = [
    		'username' => 'required|unique:users,username|max:12',
            'password' => 'required|min:6',
    		'phone' => 'telephone',
    	];
    	$this->validate($request, $rules);

        if($request->sex == '男')
        {
            $data = array_merge(['sex' => 1], $request->only(['name', 'phone']));
        }else if($request->sex == '女'){
            $data = array_merge(['sex' => 2], $request->only(['name', 'phone']));
        }else{
            $data = array_merge(['sex' => 0], $request->only(['name', 'phone']));
        }
    	UserService::add(array_merge($request->only(['username', 'password']), ['is_admin' => 1]), $data);
    	return formatJsonResponse();
    }

    public function update(Request $request)
    {
        $rules = [
            'userId' => 'required|exists:users,id',
            'phone' => 'telephone',
        ];
        $this->validate($request, $rules);

        if($request->sex == '男')
        {
            $data = array_merge(['sex' => 1], $request->only(['name', 'phone']));
        }else if($request->sex == '女'){
            $data = array_merge(['sex' => 2], $request->only(['name', 'phone']));
        }else{
            $data = array_merge(['sex' => 0], $request->only(['name', 'phone']));
        }

        UserService::updateAdminInfo($request->userId, $data);
        return formatJsonResponse();
    }

    public function delete(Request $request)
    {
    	$rules = [
    		'username' => 'required|exists:users,username',
    	];
    	$this->validate($request, $rules);

    	UserService::delete($request->username);
    	return formatJsonResponse();
    }

    public function login(Request $request)
    {
    	$rules = [
    		'username' => 'required',
    		'password' => 'required|min:6',
    	];
    	$this->validate($request, $rules);

    	UserService::login($request->only(['username', 'password']));
    	return formatJsonResponse();
    }

    public function logout(Request $request)
    {
    	UserService::logout();
    	return formatJsonResponse();
    }

    public function userInfoFindByOpenId(Request $request)
    {
        $rules = [
            'openId' => 'required|exists:wx_users,open_id',
        ];
        $this->validate($request, $rules);

        $userInfo = UserService::userInfoFindByOpenId($request->openId);
        return formatJsonResponse(['userInfo' => $userInfo]);
    }



}
